package service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import properties.MyAppConstantes;
import android.os.AsyncTask;
import android.os.Environment;
import android.webkit.WebView;
import controller.MainActivity;

public class displayReportAsyncTask extends AsyncTask<Object, Object, File> {
	private MainActivity Context = null;
	// private String result;
	private String hash;
	private String timestamp;
	File dir = Environment.getExternalStorageDirectory();
	private WebView webView;
	private File data;

	public displayReportAsyncTask(MainActivity context) {
		Context = context;
	}

	protected File doInBackground(Object... arg0) {

		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost("http://" + MyAppConstantes.WsIpServer
				+ ":8080/ab_service_mgr/api/mobile/report");

		try {
			timestamp = System.currentTimeMillis() + "";
			hash = Sha1Utils.sha(MyAppConstantes.wsSecret + timestamp);

			JSONObject json = new JSONObject();
			json.put("timestamp", timestamp);
			json.put("hash", hash);
			json.put("wsCallerId", MyAppConstantes.wsCallerId);

			StringEntity entity = new StringEntity(json.toString());

			httpPost.setEntity(entity);
			httpPost.setHeader("Content-Type", "application/xml");

			HttpResponse response = client.execute(httpPost);

			ByteArrayOutputStream outstream = new ByteArrayOutputStream();
			response.getEntity().writeTo(outstream);
			byte[] responseBody = outstream.toByteArray();

			data = new File(dir, "mydemo.pdf");
			OutputStream op = new FileOutputStream(data);
			op.write(responseBody);

			// ** lister fichiers de la sdCard
			// File[] lisFiles = dir.listFiles();
			// for (File element : lisFiles) {
			// System.out.println(element.getName());
			// }
			// System.out.println(data.exists());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

	protected void onPostExecute(File data) {	
//		Context.setContentView(R.layout.webview_report);
//		webView = (WebView) Context.findViewById(R.id.webkit);
//
//		webView.getSettings().setJavaScriptEnabled(true);
//
//		// webView.loadUrl("www.google.com");
//		webView.loadUrl(data.getAbsolutePath());
		PdfHandler pdf = new PdfHandler(Context);
		pdf.openPdf("mydemo.pdf");
	}
}
